<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <!-- 中间级联选择区 -->
      <el-row class="top">
        <el-col>
          <span>
            选择商品分类：
            <el-cascader
              v-model="sureCate"
              :options="cateList"
              :props="prop"
              @change="handleChange"
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- 下面tab标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" @click="add">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyInfo" stripe style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="deleteTag(index,scope.row)"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteInfo(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" @click="add">添加属性</el-button>
          <!--   -->
          <el-table :data="onlyInfo" stripe style="width: 100%" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  @close="deleteTag(index,scope.row)"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteInfo(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加静态属性和动态参数对话框 -->
    <el-dialog
      :title="'添加'+addInfo"
      :visible.sync="dialogVisible_addInfo"
      width="50%"
      @close="closeAddInfo"
    >
      <!-- 中间表单区域 -->
      <el-form
        :model="addInfoForm"
        :rules="addInfoFormRules"
        ref="addInfoFormRef"
        label-width="100px"
      >
        <el-form-item :label="addInfo" prop="attr_name">
          <el-input v-model="addInfoForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_addInfo = false">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+addInfo"
      :visible.sync="dialogVisible_editInfo"
      width="50%"
      @close="closeEditInfo"
    >
      <!-- 中间表单区域 -->
      <el-form
        :model="editInfoForm"
        :rules="editInfoFormRules"
        ref="editInfoFormRef"
        label-width="100px"
      >
        <el-form-item :label="addInfo" prop="attr_name">
          <el-input v-model="editInfoForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible_editInfo = false">取 消</el-button>
        <el-button type="primary" @click="sureEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择器的配置
      prop: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      // 商品分类列表数据
      cateList: [],
      //级联选中的值
      sureCate: [],
      //页签的选中值
      activeName: "many",
      //静态数据
      onlyInfo: [],
      // 动态数据
      manyInfo: [],
      //添加参数属性对话框显示与隐藏
      dialogVisible_addInfo: false,
      //添加参数对话框表单数据对象
      addInfoForm: {
        attr_name: "",
      },
      //添加参数对话框表单验证规则对象
      addInfoFormRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },

      //修改参数属性对话框显示与隐藏
      dialogVisible_editInfo: false,
      //修改参数对话框表单数据对象
      editInfoForm: {
        attr_name: "",
      },
      //修改参数对话框表单验证规则对象
      editInfoFormRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      //属性id
      attrId: 0,
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //添加参数对话框关闭触发
    closeAddInfo() {
      this.$refs.addInfoFormRef.resetFields();
    },
    //添加参数对话框点击确定触发
    sure() {
      this.$refs.addInfoFormRef.validate(async (value) => {
        if (!value) {
          return layer.msg("输入有误，请重新输入！");
        }
        if (this.activeName == "many") {
          //添加动态参数提交
        } else {
          //添加静态属性提交
        }

        const { data: res } = await this.axios.post(
          `categories/${this.sureCate[2]}/attributes`,
          {
            attr_name: this.addInfoForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        layer.msg(res.meta.msg, { time: 1000 }, () => {
          this.handleClick();
          this.dialogVisible_addInfo = false;
        });
      });
    },
    // 点击添加参数或添加属性触发
    add() {
      if (this.sureCate.length !== 3) {
        return layer.msg("请在上方选择三级商品分类后重试！");
      }
      this.dialogVisible_addInfo = true;
    },
    //切换页签触发
    handleClick() {
      if (this.sureCate.length !== 3) {
        this.sureCate = [];
        this.onlyInfo = [];
        this.manyInfo = [];
        return layer.msg("请在上方选择三级商品分类后重试！");
      }
      //动态参数
      if (this.activeName == "many") {
        const res = this.getList(this.sureCate[2], "many");
        res.then((value) => {
          this.manyInfo = value;
        });
        //静态参数
      } else if (this.activeName == "only") {
        const res = this.getList(this.sureCate[2], "only");
        res.then((value) => {
          this.onlyInfo = value;
        });
      }
    },
    //级联选择框发生改变
    handleChange(value) {
      this.handleClick();
    },
    //获取级联选择框获取商品分类
    async getCateList() {
      const { data: res } = await this.axios.get("categories");
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      this.cateList = res.data;
    },
    //发送请求获取参数
    async getList(id, sel) {
      const { data: res } = await this.axios.get(
        `categories/${id}/attributes`,
        {
          params: { sel: sel },
        }
      );
      if (res.meta.status !== 200) {
        layer.msg(res.meta.msg, { time: 1000 });
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      return res.data;
    },
    //点击修改按钮
    async showEdit(id) {
      this.attrId = id;
      const { data: res } = await this.axios.get(
        `categories/${this.sureCate[2]}/attributes/${id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      this.editInfoForm.attr_name = res.data.attr_name;
      this.dialogVisible_editInfo = true;
    },
    //关闭修改对话框
    closeEditInfo() {
      this.$refs.editInfoFormRef.resetFields();
    },
    //提交修改
    sureEdit() {
      this.$refs.editInfoFormRef.validate(async (value) => {
        if (!value) {
          return layer.msg("输入有误，请重新输入！");
        }
        const { data: res } = await this.axios.put(
          `categories/${this.sureCate[2]}/attributes/${this.attrId}`,
          {
            attr_name: this.editInfoForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        layer.msg(res.meta.msg, { time: 1000 }, () => {
          this.handleClick();
          this.dialogVisible_editInfo = false;
        });
      });
    },
    //删除按钮
    deleteInfo(id) {
      layer.confirm(
        "此操作将永久删除该分类, 是否继续?  ",
        { icon: 3, title: "提示" },
        async (index) => {
          const { data: res } = await this.axios.delete(
            `categories/${this.sureCate[2]}/attributes/${id}`
          );
          if (res.meta.status !== 200) {
            return layer.msg(res.meta.msg, { time: 1000 });
          }
          layer.msg(res.meta.msg, { time: 1000 }, () => {
            this.handleClick();
            layer.close(index);
          });
        }
      );
    },
    //tag文本框失去焦点或者按enter触发
    async handleInputConfirm(value) {
      if (value.inputValue.trim().length === 0) {
        value.inputValue = "";
        value.inputVisible = false;
        return;
      }
      value.attr_vals.push(value.inputValue.trim());
      value.inputValue = "";
      value.inputVisible = false;
      //发起请求保存
      const { data: res } = await this.axios.put(
        `categories/${this.sureCate[2]}/attributes/${value.attr_id}`,
        {
          attr_name: value.attr_name,
          attr_sel: value.attr_sel,
          attr_vals: value.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      layer.msg(res.meta.msg, { time: 1000 });
    },
    //点击添加标签显示输入框
    showInput(row) {
      row.inputVisible = true;
      //文本框自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //删除小标签
    async deleteTag(index, value) {
      value.attr_vals.splice(index, 1);
      //发起请求保存
      const { data: res } = await this.axios.put(
        `categories/${this.sureCate[2]}/attributes/${value.attr_id}`,
        {
          attr_name: value.attr_name,
          attr_sel: value.attr_sel,
          attr_vals: value.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      layer.msg(res.meta.msg, { time: 1000 });
    },
  },
  //计算属性
  computed: {
    addInfo() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>
<style scoped>
.top {
  margin: 20px 0;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>